package fwk.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import fwk.Controller;
import fwk.HandlerAdapter;
import fwk.HandlerMapping;
import fwk.ViewResolver;

public class BeanFactory {
	private  String config;
	public static final  String HANDLER_MAPPING_NAME="handlerMapping";
	public static final  String VIEW_RESOVER_NAME="viewResover";
	public static final  String HANDLER_ADAPTER_NAME="handlerAdapter";

	private Map<String, Object> beanMap=new HashMap<String, Object>();
	
	public BeanFactory(String config){
		this.config=config;
		try {
			createObjects();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public Object getBean(String beanName){
		return beanMap.get(beanName);
	}
	public void createObjects() throws Exception{
		Document doc=new SAXBuilder().build(config);
		List<Element> beanEles= doc.getRootElement().getChildren("bean");
		for(Element beanEle:beanEles){
			String name=beanEle.getAttributeValue("name");
			String className=beanEle.getAttributeValue("class");
			//反射生成对象
			Object o=Class.forName(className).newInstance();
			if(o instanceof HandlerMapping){
				name=HANDLER_MAPPING_NAME;
			}
			if(o instanceof HandlerAdapter){
				name=HANDLER_ADAPTER_NAME;
			}
			if(o instanceof ViewResolver){
				name=VIEW_RESOVER_NAME;
			}
			if(o instanceof Controller){
				((HandlerMapping)getBean(HANDLER_MAPPING_NAME)).addMap(name, (Controller)o);
			}
			beanMap.put(name, o);
			
		}
		
		
	}
	
	public static void main(String[] args) throws Exception{
		BeanFactory bf = new BeanFactory("application.xml");
		bf.createObjects();
	}
}









